﻿using Common;
using Common.Inet;
using DadayunApi.Model;
using KbtSync.BLL;
using KbtSync.DAL;
using KbtSync.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace StorageSync
{
    class Program
    {
        //private static DadayunDAL ddyDal;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args">args[0] 每页数量,缺省100</param>
        static void Main(string[] args)
        {
            bool autoMode = false;
            int forcePrdQty = 0;
            foreach (string a in args)
            {
                if(a=="/a")
                {
                    autoMode = true;
                }
                if(Regex.IsMatch(a, @"^[1-9]\d*$"))
                {
                    forcePrdQty = int.Parse(a);
                }
            }
            int pageSize = 20;
            if( args.Length>0)
            {
                int.TryParse(args[0], out pageSize);
            }
            string baseUri = "";
            string erpConnStr = "";
            string reportToEmail = "dejex@kenbotong.com";
            string mailBodyText = "";
            AppAuthBase appAuth = null;
            string settingFile = "settings.ini";
            Console.WriteLine("搭搭云库存同步器 1.0.2 Copyright(c) CCJungle, 2018");
            Console.WriteLine(DateTime.Now.ToString());
            Console.WriteLine("语法：StorageSync [QTY] [/a]");
            Console.WriteLine("  QTY-取出前QTY条产品做库存同步 /a - 自动模式，中途没有中止机会");
            Console.WriteLine("检查系统设置...");
            mailBodyText = "搭搭云库存同步器 1.0.2 Copyright(c) CCJungle, 2018\r\n" +
                DateTime.Now + "检查系统设置...";
            if (File.Exists(settingFile))
            {
                MyConfiguration cfg = new MyConfiguration(true);
                cfg.Load(settingFile);
                if (cfg.ContainsKey(SettingItems.erpDbConnString))
                {
                    erpConnStr = cfg.ReadString(SettingItems.erpDbConnString);
                }
                appAuth = new AppAuthBase();
                if (cfg.ContainsKey(SettingItems.ddyBaseUri)) baseUri = cfg.ReadString(SettingItems.ddyBaseUri);
                if (cfg.ContainsKey(SettingItems.ddyTenantName)) appAuth.TenantName = cfg.ReadString(SettingItems.ddyTenantName);
                if (cfg.ContainsKey(SettingItems.ddyUsername)) appAuth.Username = cfg.ReadString(SettingItems.ddyUsername);
                if (cfg.ContainsKey(SettingItems.ddyPasswd)) appAuth.Password = cfg.ReadString(SettingItems.ddyPasswd);
                if (cfg.ContainsKey(SettingItems.ddyAppKey)) appAuth.AppKey = cfg.ReadString(SettingItems.ddyAppKey);
                if (cfg.ContainsKey(SettingItems.ddySecret)) appAuth.AppSecret = cfg.ReadString(SettingItems.ddySecret);
                if (cfg.ContainsKey(SettingItems.ddyPubkey)) appAuth.PublicKey = cfg.ReadString(SettingItems.ddyPubkey);
                if (cfg.ContainsKey(SettingItems.reportToEmail)) reportToEmail = cfg.ReadString(SettingItems.reportToEmail);
                DdySyncBLL bLL = new DdySyncBLL(erpConnStr, baseUri, appAuth);
                if(!bLL.IsErpReady())
                {
                    string  errmsg = "ERP服务器无法连接,无法执行库存同步任务!";
                    errmsg += "\r\n 请运行KbtSyncTest检查ERP服务器连接设置";
                    MyLog.WriteError("同步库存", errmsg);
                    Console.WriteLine(errmsg);
                    mailBodyText += "\r\n" + errmsg;
                }
                else if(!bLL.IsDdyReady())
                {
                    string errmsg = "搭搭云服务器无法连接,无法执行库存同步任务!";
                    errmsg += "\r\n 请检查网络连接或运行KbtSyncTest检查DDY服务器连接设置";
                    MyLog.WriteError("同步库存", errmsg);
                    Console.WriteLine(errmsg);
                    mailBodyText += "\r\n" + errmsg;
                }
                else
                {
                    Console.WriteLine("系统检查通过,开始库存同步...");
                    DateTime start = DateTime.Now;
                    string msg = "同步开始于" + DateTime.Now.ToLongTimeString();
                    MyLog.WriteInfo("开始同步库存", msg);
                    mailBodyText += "\r\n" + msg;
                    try
                    {
                        IList<ProductReportResult> products = bLL.GetProductList();
                        msg = "从CRM服务器上获取到" + products.Count + "条产品";
                        MyLog.WriteInfo("获取到产品！", msg);
                        mailBodyText += "\r\n" + msg;
                        Console.WriteLine(msg);
                        if (!autoMode) {
                            Console.WriteLine("输入任意键继续...");
                            Console.ReadKey();
                        }
                        
                        if(forcePrdQty!=0)
                        {
                            products = products.Take(forcePrdQty).ToList();
                            msg = "从中提取" + forcePrdQty + "条产品";
                            MyLog.WriteInfo("从中提取到产品！", msg);
                            mailBodyText += "\r\n" + msg;
                            Console.WriteLine(msg);
                            if (!autoMode)
                            {
                                Console.WriteLine("输入任意键继续...");
                                Console.ReadKey();
                            }
                        }
                        int count = bLL.StorageSyncBatchMode(products, pageSize, out int errCount);
                        TimeSpan ts = DateTime.Now - start;
                        msg = " 同步产品数量: " + count + ",耗时:" + ts.TotalSeconds;
                        MyLog.WriteInfo("完成同步库存", msg);
                        mailBodyText += "\r\n" + msg;
                        Console.WriteLine(msg);
                    }
                    catch (Exception ex)
                    {                        
                        MyLog.WriteInfo("库存同步失败", ex.Message);
                        mailBodyText += "\r\n" + msg;
                        Console.WriteLine(msg);
                    }
                   // var ans = bLL.StorageSyncBatchMode(out int count);
                }
                
            }
            else
            {
                string msg = "缺少配置文件,无法执行库存同步任务,请先运行KbtSync生成配置文件,并拷贝至程序目录!";
                MyLog.WriteError("同步库存", msg);
                mailBodyText += "\r\n" + msg;
                Console.WriteLine(msg);
               
            }
#if DEBUG

#else
            SendTextMail("搭搭云库存同步器报告", mailBodyText, reportToEmail);
#endif

        }


        protected static void SendTextMail(string title,string body,params string[] addresses)
        {
            Email email = new Email
            {
                mailFrom = "dejex@kenbotong.com",
                mailPwd = "tech8046",
                mailSubject = title,
                host = "mail.kenbotong.com",//如果是QQ邮箱则：smtp.qq.com,依次类推
                mailToArray = addresses
            };
            email.mailBody = body;            
            email.isbodyHtml = false;    //是否是HTML
            email.Send();
        }
        
    }
    class SettingItems
    {//本类与KbtSyncTest的同名类相同，为了调取其配置文件
        public static string erpDbConnString = "ErpDbConnString";
        public static string ddyBaseUri = "DdyBaseUri";
        public static string ddyTenantName = "DdyTenantName";
        public static string ddyUsername = "DdyUsername";
        public static string ddyPasswd = "DdyPasswd";
        public static string ddyAppKey = "DdyAppKey";
        public static string ddySecret = "DdySecret";
        public static string ddyPubkey = "DdyPubkey";
        public static string reportToEmail = "ReportToEmail";
    }
}
